package com.wangxl;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 练习Map的各种操作
 * @author wangxl
 * @date 2022/2/17 13:03
 */
@Slf4j
public class MapOperate {

    /**
     * 主函数
     * @param args 参数
     */
    public static void main(String[] args) {
        // 班级map
        Map<Integer,String> classMap = new HashMap<>();

        // 添加数据
        classMap.put(1001, "张三");
        classMap.put(1002, "李四");
        classMap.put(1003, "王五");
        classMap.put(1004, "钱六");

        log.info("添加数据后，classMap = " + classMap);

        // 读取数据
        // 学生姓名
        String studentName = classMap.get(1003);

        log.info("读取到的数据是：" + studentName);

        // 1、在for循环中遍历key或者value
        long startTime1 = System.nanoTime();
        for (int key : classMap.keySet()){
            System.out.println(key);
        }
        for (String value : classMap.values()){
            System.out.println(value);
        }
        long endTime1 = System.nanoTime();
        long useTime1 = endTime1 - startTime1;

        log.info("在for循环中遍历key或者value，用时：" + useTime1);

        // 2、通过键找值遍历
        long startTime2 = System.nanoTime();
        for (int key : classMap.keySet()){
            String value = classMap.get(key);
            System.out.println(key + " " + value);
        }
        long endTime2 = System.nanoTime();
        long useTime2 = endTime2 - startTime2;

        log.info("通过键找值遍历，用时：" + useTime2);

        // 3、java8 Lambda
        long startTime3 = System.nanoTime();
        classMap.forEach((key,value) -> {
            System.out.println(key + " " + value);
        });
        long endTime3 = System.nanoTime();
        long useTime3 = endTime3 - startTime3;

        log.info("java8 Lambda，用时：" + useTime3);

        // 4、通过Iterator遍历
        long startTime4 = System.nanoTime();
        Iterator<Map.Entry<Integer,String>> entries = classMap.entrySet().iterator();
        while (entries.hasNext()){
            Map.Entry<Integer,String> entry = entries.next();
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " " + value);
        }
        long endTime4 = System.nanoTime();
        long useTime4 = endTime4 - startTime4;

        log.info("通过Iterator遍历，用时：" + useTime4);

        // 5、entrySet遍历
        long startTime5 = System.nanoTime();
        for (Map.Entry<Integer,String> entry : classMap.entrySet()){
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " " + value);
        }
        long endTime5 = System.nanoTime();
        long useTime5 = endTime5 - startTime5;

        log.info("entrySet遍历，用时：" + useTime5);

    }

}
